package pe.com.bbva.ge.utileria.drools;

import java.util.ArrayList;
import java.util.List;

import org.drools.command.Context;
import org.drools.command.impl.GenericCommand;
import org.drools.command.impl.KnowledgeCommandContext;
import org.drools.event.rule.AfterActivationFiredEvent;
import org.drools.event.rule.DefaultAgendaEventListener;
import org.drools.runtime.StatefulKnowledgeSession;

import pe.com.bbva.ge.domain.base.BaseDomain;
import pe.com.bbva.ge.domain.configuracion.Regla;

public class ComandoDrools extends DefaultAgendaEventListener implements GenericCommand<Integer>{

	/**
	 * 
	 */
	private static final long serialVersionUID = 8793012334195409789L;
	
	private List<String> reglasEjecutadas;
	
	private List<BaseDomain> objetos;
	
	private List<Regla> reglas;

	public ComandoDrools(List<BaseDomain> objetos, List<Regla> reglas) {
		super();
		this.objetos = objetos;
		this.reglas = reglas;
	}

	@Override
	public Integer execute(Context context) {
		
		reglasEjecutadas = new ArrayList<String>();
		
		StatefulKnowledgeSession ksession = ((KnowledgeCommandContext) context).getStatefulKnowledgesession();
		ksession.addEventListener(this);
		
		for (BaseDomain beanBase : objetos) {
        	ksession.insert(beanBase);
		}		
		
		FilterDrools filterDrools = new FilterDrools(reglas);
		
		return ksession.fireAllRules(filterDrools);
	}
	
	@Override
	public void afterActivationFired(AfterActivationFiredEvent event) {
		String codigoRegla = event.getActivation().getRule().getName();
		reglasEjecutadas.add(codigoRegla);
	}

	public List<String> getReglasEjecutadas() {
		return reglasEjecutadas;
	}	

}
